﻿using System;
using System.Collections.Generic;
using System.Text;
using Kugar.Tool.Web.RequestFieldValidation.Resources;
using Microsoft.Extensions.Localization;

namespace Kugar.Tool.Web.RequestFieldValidation.Rules
{
    public class StringLengthRule:RuleBase
    {
        public StringLengthRule(int maxLength,int minLength, string errorMsg,bool asciiLength=false) : base(errorMsg)
        {
            MaxLength = maxLength;
            MinLength = minLength;
            IsAscIILength = asciiLength;
        }

        public int MaxLength { get; }

        public int MinLength { get; }

        public bool IsAscIILength { get; }

        protected override string BuildDefaultErrorMessage(IRequestField field)
        {
            if (MaxLength > 0 && MinLength > 0)
            {
                return Localizer["输入长度必须介于 {0} 和 {1} 之间的字符串",MinLength,MaxLength];//$"输入长度必须介于 {MinLength} 和 {MaxLength} 之间的字符串";
            }

            if (MaxLength > 0)
            {
                return Localizer["输入长度最多是 {0} 的字符串",  MaxLength];//$"输入长度最多是 {MaxLength} 的字符串";
            }

            if (MinLength > 0)
            {
                return Localizer["输入长度最小是 {0} 的字符串", MinLength];//$"输入长度最小是 {MinLength} 的字符串";
            }

            return "";
        }

        protected override bool ValidateField(IRequestField field)
        {
            var f = (IRequestField<string>) field;

            var value = f.Value();

            if (string.IsNullOrWhiteSpace(value))
            {
                return true;
            }

            if (MinLength>0)
            {
                if ((value?.Length??0)<MinLength)
                {
                    return false;
                }

                if (IsAscIILength && (value?.Length??0) > 0 && Encoding.ASCII.GetByteCount(value) < MinLength)
                {
                    return false;
                }
            }

            if (MaxLength>0)
            {
                if (value?.Length>MaxLength)
                {
                    return false;
                }

                if (IsAscIILength && (value?.Length??0)>0 && Encoding.ASCII.GetByteCount(value)>MaxLength)
                {
                    return false;
                }
            }

            return true;

        }
    }
}
